<template>
	<view class="company_album">
		<view class="ca_tabs" v-if="tabs.length != 0">
			<view class="ca_tabs_left">
				<view @click="changeTabs(index)"
					:class="currentTabs == index ? 'atl_item_active atl_item f13' : 'atl_item f13'"
					v-for="(item,index) in tabs" :key="index">
					{{item.title}}
				</view>
			</view>
		</view>
		<view v-if="tabs.length != 0 && currentTabs == 0 && tabs[currentTabs].list">
			<view class="shebei mt10" v-for="(item,index) in tabs[currentTabs].list" :key="index">
				<view v-if="item.title.indexOf('文件') == -1">
					<view class="f600 f18 mb10">
						{{item.title}}
					</view>
					<view class="img_box df " v-if="page_width">
						<view class="img_sty" v-for="(items,idx) in item.list" :key="idx"
							:style="'width:'+ comImgWidth(3) + 'rpx;height:' + comImgWidth(3) + 'rpx;'"
							@click="previewImg(item,idx)">
							<image style="width:100%;height:100%" :src="getImgSrc(items)" mode="aspectFill" />
						</view>
					</view>
				</view>
				<view v-else>
					<view class="f600 f18 mb10">
						{{item.title}}
					</view>
					<view class="fileBox" v-for="(item, index) in item.list" :key="index">
						<view class="fileNum mr10">
							{{index + 1}}
						</view>
						<view class="file-box df ac sb">
							<image class="img16" src="/static/img/file.png"></image>
							<p class="f14 c28 ml8 w224 ovh">{{ item.name }}</p>
							<p class="f12 c10" @tap.native="onLook($event, { i: index })" :data-i="index"
								v-if="changeBtn(item.url)">在线预览</p>
							<p class="f12 c10" @tap.native="onLook($event, { i: index })" :data-i="index" v-else>转发好友
							</p>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view v-else-if="tabs.length != 0 && currentTabs != 0 && tabs[currentTabs].title.indexOf('文件') == -1"
			class="mt10">
			<view class="f600 f18 mb10">
				{{tabs[currentTabs].title}}
			</view>
			<view class="img_box df " v-if="page_width">
				<view class="img_sty" v-for="(item,index) in tabs[currentTabs].list" :key="index"
					:style="'width:'+ comImgWidth(3) + 'rpx;height:' + comImgWidth(3) + 'rpx;'"
					@click="preview(item,index)">
					<image style="width:100%;height:100%" :src="getImgSrc(item)" mode="aspectFill" />
				</view>
			</view>
		</view>
		<view v-else-if="tabs.length != 0 && currentTabs != 0">
			<view class="f600 f18 mb10">
				{{tabs[currentTabs].title}}
			</view>
			<view class="img_box " v-if="page_width">
				<view class="df ac" style="width:100%;" v-for="(item, index) in tabs[currentTabs].list" :key="index">
					<view class="fileNum mr10">
						{{index + 1}}
					</view>
					<view class="file-box df ac sb">
						<image class="img16" src="/static/img/file.png"></image>
						<p class="f14 c28 ml8 w224 ovh">{{ item.name }}</p>
						<p class="f12 c10" @tap.native="onLook($event, { i: index })" :data-i="index"
							v-if="changeBtn(item.url)">在线预览</p>
						<p class="f12 c10" @tap.native="onLook($event, { i: index })" :data-i="index" v-else>转发好友</p>
					</view>
				</view>
			</view>
		</view>
		<view v-else></view>

		<van-popup custom-style="height: 60%" position="bottom" round :show="show" round @close="show = false">
			<span class="f16 c28 f500 db tc mt20 mt5" style="margin-bottom: 40rpx;">免责声明</span>
			<view class="xy-box1  mt10 mb10">
				<view class="xy-content">
					<view class="mt10" style="line-height: 50rpx;">
						所有图片、文件信息来源于平台用户。夕腾外协不保证平台上任何内容的合法合规性、安全性、真实性、正当性、准确性和及时性，并不承担与该信息相关的任何连带责任。 </view>
					<view class="mt10" style="line-height: 50rpx;">
						任何单位或个人认为夕腾外协平台上的信息侵犯了自己的合法权利(如著作权、信息网络传播权、隐私权等)时，请及时向夕腾外协发出书面通知(请发邮件至xtwaixie@qq.com)，并提供真实身份证明、权属证明及详细侵权情况证明。夕腾外协将在收到上述文件后，根据核查结果决定是否删除相关信息。
					</view>
				</view>
			</view>
		</van-popup>
		<slider-verify :isShow="sliderVerifyFLag" @touchSliderResult="verifyResult" ref="verifyElement"></slider-verify>
		<van-popup :show="show2" round>
			<p class="db pd200 mt5 w311">
				<span class="f16 c28 f500 db tc">确定下载？</span>
			</p>
			<view class="df ac btf1 h48">
				<p class="w50 tc f16 c28" @tap.native="show2 = false">取消</p>
				<button class="share-but1 h48 c10" @tap="forward">确定</button>
			</view>
		</van-popup>
	</view>
</template>
<script>
	const http = require('../../utils/http');

	import sliderVerify from '@/component/slider-verify.vue'; //组件存放的路径
	export default {
		components: {
			sliderVerify
		},
		data() {
			return {
				page_width: 0,
				img: [],
				file: [],
				company: '',
				lj_name: '',
				name: [],
				sliderVerifyFLag: false,
				show2: false,
				loading: false,
				show: false,
				isPc: false,
				img_path: http.img_path,
				// tabs: [{
				// 	title: '全部',
				// 	list: []
				// }, {
				// 	title: '公司环境',
				// 	list: []
				// }, {
				// 	title: '设备车间',
				// 	list: []
				// }, {
				// 	title: '附件',
				// 	list: []
				// }],
				tabs: [],
				currentTabs: 0,
				showPopup: false,
				img2: [],
				id: 0,
				fileName: [],
				equipment_img: [],
				other_img: [],
				userInfo: null
			};
		},
		onLoad(option) {
			this.getInfo(option.id)
			this.getSystemInfo()

		},
		methods: {
			copy() {
				http.request('demand/getIp', {
					type: 1,
					id: this.id,
				}).then((res) => {
					let text = http.url +
						`/h5/?#/?decrypt=${this.decrypt}${this.index == 1 ? '&index=1':''}&decrypt_time=${this.decrypt_time}`
					uni.setClipboardData({
						data: text,
						success(res) {
							uni.showToast({
								title: '复制成功',
								icon: 'none'
							});
						},
						fail(err) {
							console.log(err);
						}
					});
				}).catch((res) => {
					console.log(res);
				});
			},
			// 预览
			previewImg(item, index) {
				console.log(item)
				let urls = []
				item.list.forEach(items => {
					if (items) {
						urls.push(this.getImgSrc(items))
					}
				})
				uni.previewImage({
					current: index,
					urls: urls
				});
			},
			preview(index) {
				let urls = []
				this.tabs[this.currentTabs].list.forEach(items => {
					if (items) {
						urls.push(this.getImgSrc(items))
					}
				})
				uni.previewImage({
					current: index,
					urls: urls
				});
			},
			getInfo(id) {
				http.request('user/settledInfo', {
					id
				}).then((res) => {
					this.userInfo = res.data.info.userInfo
					const fList = res.data.info.detail.file_list || []
					if (fList && fList.length != 0) {
						this.name = fList.map(item => item.name) || []
						this.file = fList.map(item => this.getImgSrc(item.url)) || []
					}

					// this.lj_name = res.data.info.detail.introduction
					this.id = res.data.info.uid
					const {
						company_environment,
						equipment_img,
						other_img
					} = res.data.info.detail || []
					this.tabs = [{
							title: '全部',
							list: []
						},
						{
							title: `车间展示(${company_environment.length})`,
							list: company_environment
						},
						{
							title: `设备展示(${equipment_img.length})`,
							list: equipment_img
						},
						{
							title: `文件(${fList.length})`,
							list: fList
						}
					]
					if (other_img) {
						this.tabs.push({
							title: `其他(${other_img?.length?other_img.length:0})`,
							list: other_img
						})
					}
					this.tabs = this.tabs.filter(item => item.title === '全部' || item.list.length > 0);
					const allTab = {
						title: `全部(0)`,
						list: []
					};
					console.log(this.tabs)
					let totalLength = 0;
					this.tabs.forEach((tab, index) => {
						if (index > 0) {
							totalLength += tab.list.length;
							allTab.list.push({
								title: tab.title,
								list: [...tab.list]
							});
						}
					})
					allTab.title = `全部(${totalLength})`;
					this.tabs[0] = allTab;

					http.request('demand/getIp', {
							type: 1,
							id: res.data.info.uid,
						})
						.then((res) => {
							return
							let text = http.url +
								`/h5/?#/?decrypt=${this.decrypt}${this.index == 1 ? '&index=1':''}&decrypt_time=${this.decrypt_time}`
							uni.setClipboardData({
								data: text,
								success(res) {
									uni.showToast({
										title: '复制成功',
										icon: 'none'
									});
								},
								fail(err) {
									console.log(err);
								}
							});
						})
						.catch((res) => {
							console.log(res);
						});
					console.log(this.fileName)
					let data = res.data.info
					let status = !!data.detail
					if (status) {
						data = {
							...data,
							...data.detail
						}
					}
					this.company = data.company
					// this.tabs.map(item => item.list = [])
					// if (data.doorboard) {
					// 	this.tabs[0].list = [data.doorboard]
					// }
					// if (data.company_environment) {
					// 	this.tabs[0].list = this.tabs[0].list.concat(data.company_environment)
					// 	this.tabs[1].list = data.company_environment
					// }
					// if (data.equipment_img) {
					// 	this.tabs[0].list = this.tabs[0].list.concat(data.equipment_img)
					// 	this.tabs[2].list = data.equipment_img
					// }
					// if (data.file_list) {
					// 	this.tabs[3].list = data.file_list
					// }
				}).catch((res) => {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				});
			},
			changeBtn(item) {
				let typeList = ['doc', 'xls', 'ppt', 'pdf', 'PDF', 'docx', 'xlsx', 'pptx']
				let result = false
				typeList.forEach((res) => {
					if (item.split('.')[item.split('.').length - 1] == res) {
						result = true
					}
				})
				return result
			},

			onLook(e, _dataset) {
				if (this.loading) {
					return
				}
				this.loading = true
				setTimeout(() => {
					this.loading = false
				}, 1000);
				/* ---处理dataset begin--- */
				this.handleDataset(e, _dataset);
				/* ---处理dataset end--- */
				let i = e.currentTarget.dataset.i;
				let url = this.file[i];
				const status = this.changeBtn(url)
				const extension = this.getFileExtension(url);
				const randfile = this.name[i].endsWith('.' + extension) ? this.name[i] : this.name[i] + '.' + extension
				const newPath = `${wx.env.USER_DATA_PATH}/${randfile}`;
				let showMenu = this.userInfo.grade == 2;
				uni.showLoading({
					title: '文件下载中'
				});
				console.log('下载链接：', url)
				console.log('保存路径：', newPath)
				uni.downloadFile({
					url: url,
					filePath: newPath,
					success(res) {
						console.log(res);
						if (res.statusCode === 200) {
							if (status) {
								uni.openDocument({
									filePath: res.filePath || res.tempFilePath,
									showMenu: showMenu,
									success(res) {
										// console.log(res);
										console.log('打开/文档成功');
										uni.hideLoading();
									},
									fail(res) {
										console.log(res);
										uni.hideLoading();
									}
								});
							} else {
								uni.shareFileMessage({
									filePath: res.filePath || res.tempFilePath,
									success(res) {
										// console.log(res);
										uni.hideLoading();
									},
									fail(res) {
										console.log(res);
										uni.hideLoading();
									}
								});
							}
						} else {
							uni.hideLoading();
						}
					},
					fail(res) {
						console.log(res);
						uni.hideLoading();
					}
				});
			},
			getFileExtension(filePath) {
				// 使用最后一个点和文件名的分隔符来获取文件名
				const filename = filePath.split('/').pop();
				// 获取文件名中的后缀部分
				const extension = filename.split('.').pop();
				return extension;
			},
			verifyResult(res) {
				this.sliderVerifyFLag = false;
				if (res) { //校验通过
					this.show2 = true
				}
			},
			forward() {
				if (this.loading) {
					return
				}
				this.show = false
				this.show2 = false
				this.loading = true
				uni.showLoading({
					title: '文件下载中'
				});
				setTimeout(() => {
					this.loading = false
				}, 1000);
				if (this.file.length + this.img.length === 1) {
					let url = '';
					let filePath = ''
					if (this.file.length > 0) {
						url = this.file[0]
						const extension = this.getFileExtension(url);
						const randfile = this.name[0].endsWith('.' + extension) ? this.name[0] : this.name[0] + '.' +
							extension
						filePath = `${wx.env.USER_DATA_PATH}/${randfile}`;
					} else {
						url = this.img2[0]
						filePath = wx.env.USER_DATA_PATH + this.img2[0].substring(this.img2[0].lastIndexOf('/'));
					}
					uni.downloadFile({
						url: url,
						filePath,
						success(res) {
							if (res.statusCode === 200) {
								uni.shareFileMessage({
									filePath: res.filePath || res.tempFilePath,
									success(res) {
										// console.log(res);
										uni.hideLoading();
									},
									fail(res) {
										uni.showToast({
											title: '分享失败1',
											icon: 'none'
										});
										uni.hideLoading();
									}
								});
							} else {
								uni.showToast({
									title: '分享失败2',
									icon: 'none'
								});
								uni.hideLoading();
							}
						},
						fail(res) {
							uni.showToast({
								title: '分享失败3',
								icon: 'none'
							});
							uni.hideLoading();
						}
					})
					return
				}
				http.request('demand/getIp', {
					type: 1,
					id: this.id,
					name: this.lj_name,
					file: this.file || [],
					fileName: this.name || [],
					img: this.img2 || [],
				}).then((res) => {
					const url = res.data.url
					uni.downloadFile({
						url: http.url + url,
						filePath: wx.env.USER_DATA_PATH + url.substring(url.lastIndexOf('/')),
						success(res) {
							if (res.statusCode === 200) {
								uni.shareFileMessage({
									filePath: res.filePath || res.tempFilePath,
									success(res) {
										console.log(res);
										http.request('demand/unlink', {
											url
										})
										uni.hideLoading();
									},
									fail(res) {
										console.log(res);
										http.request('demand/unlink', {
											url
										})
										uni.showToast({
											title: '分享失败4',
											icon: 'none'
										});
										uni.hideLoading();
									}
								});
							} else {
								http.request('demand/unlink', {
									url
								})
								uni.showToast({
									title: '分享失败5',
									icon: 'none'
								});
								uni.hideLoading();
							}
						},
						fail(res) {
							console.log(res)
							http.request('demand/unlink', {
								url
							})
							uni.showToast({
								title: '分享失败6',
								icon: 'none'
							});
							uni.hideLoading();
						}
					})
				}).catch((res) => {
					console.log(res);
					uni.hideLoading();
				});
			},
			changeTabs(i) {
				this.currentTabs = i
			},
			getSystemInfo() {
				const that = this
				uni.getSystemInfo({
					success: res => {
						that.page_width = res.screenWidth
					}
				})
			},
			comImgWidth(num) {
				const elem = (this.page_width - 100) * 2
				const width = elem / num
				return width
			},
		}
	}
</script>
<style lang="scss">
	.img_box {
		flex-wrap: wrap;

		.img_sty {
			border-radius: 8rpx;
			overflow: hidden;
		}

		&>view {
			width: 32%;
			margin-right: 15rpx;
			margin-bottom: 15rpx;
		}

		&>view:nth-child(3n) {
			margin-right: 0rpx;
		}
	}

	.tipContent {
		color: #9DA3B0;
		font-size: 24rpx;
	}

	.tipTitle {
		color: #283043;
		font-size: 28rpx;
		margin-bottom: 20rpx;
	}

	.fileTips {
		padding: 20rpx 0;
		margin-top: 20rpx;
		background-color: #f7f8fc;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.tips {
		color: #1050c7;
		font-size: 24rpx;
		text-decoration: underline;
	}

	.company_album {
		padding: 20rpx;
		box-sizing: border-box;

		.ca_tabs {
			display: flex;

			.ca_tabs_left {
				flex: 1;
				display: flex;
				flex-wrap: wrap;
				// justify-content: space-between;

				.atl_item {
					background: #F5F6FA;
					padding: 12rpx 34rpx;
					border-radius: 10rpx;
					box-sizing: border-box;
					font-size: 28rpx;
					margin-right: 20rpx;
					margin-bottom: 20rpx;
				}

				.atl_item_active {
					background: $xt-primary !important;
					color: #fff !important;
				}
			}

			.ca_tabs_right {
				// width: 80rpx;
				display: flex;
				justify-content: flex-end;

				image {
					width: 55rpx;
					height: 55rpx
				}
			}
		}

		.album_list {
			margin-top: 20rpx;
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;

			.al_item {
				width: 48%;
				height: 220rpx;
				border: 2rpx solid rgba(0, 0, 0, 0.05);
				margin-bottom: 20rpx;

				// background-color: #468CB2;
				image {
					width: 100%;
					height: 100%;
				}
			}
		}
	}

	.fileBox {
		display: flex;
		// justify-content: space-between;
		align-items: center;
	}

	.fileNum {
		color: #9DA3B0;
	}

	.tipBtn {
		background-color: #68BF7B;
		width: 300rpx;
		border-radius: 16rpx;
		font-size: 28rpx;
		color: #FFF;
		text-align: center;
		line-height: 70rpx;
		font-weight: bold;
		margin: 0 20rpx 20rpx;
	}

	.share-but1 {
		width: 50% !important;
		font-size: 32rpx;
		padding: 0 !important;
		margin: 0 !important;
		font-weight: 400;
		text-align: center;
		color: #283043;
		line-height: 96rpx;
		border-left: 1rpx solid #ebedf0;
	}
</style>